package logic

import (
	"context"
	"home-manage/model"

	"home-manage/homerpc/homerpc"
	"home-manage/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HouseListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHouseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HouseListLogic {
	return &HouseListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HouseListLogic) HouseList(in *homerpc.HoseListRequest) (*homerpc.HoseListResponse, error) {
	// todo: add your logic here and delete this line

	var houses []model.HouseName
	offset := (in.Page - 1) * in.Size
	tx := model.DB.Debug().
		Model(&model.House{}).
		Offset(int(offset)).
		Limit(int(in.Size)).
		Select("houses.*,users.username as user_name").
		Joins("left join users on houses.user_id = users.id").
		Find(&houses)

	if in.PriceOrder == 1 {
		tx = tx.Order("money desc")
	}
	if in.PriceOrder == 2 {
		tx = tx.Order("money asc")
	}
	if in.CreateAtOrder == 1 {
		tx = tx.Order("created_at desc")
	}
	if in.CreateAtOrder == 2 {
		tx = tx.Order("created_at asc")
	}
	if in.StartMi > 0 {
		tx = tx.Where("num>=?", in.StartMi)
	}
	if in.EndMi > 0 {

		tx = tx.Where("num<=?", in.EndMi)
	}

	if in.Address != "" {
		tx = tx.Where("address like ?", "%"+in.Address+"%")
	}
	tx.Find(&houses)
	var houseList []*homerpc.HostList
	for _, house := range houses {

		list := homerpc.HostList{
			UserId:   int64(house.UserId),
			Title:    house.Title,
			Lease:    house.Lease,
			Money:    float32(house.Money),
			Deposit:  house.Deposit,
			Num:      float32(house.Num),
			Facility: house.Facility,
			Address:  house.Address,
			UserName: house.UserName,
		}
		houseList = append(houseList, &list)
	}
	return &homerpc.HoseListResponse{
		List: houseList,
	}, nil
}
